package typetcp

import (
	"log"
	"strings"
	"sync"
	"time"

	"github.com/jlaffaye/ftp"
)

var (
	connections = make(map[string]*ftp.ServerConn)
	lock        = sync.RWMutex{}
	used        = 0
	Repeat      = []Ftp{}
)

type Ftp string

func (ftpb Ftp) Brute() bool {

	auth, err := ParseStringToBrute(string(ftpb))
	if err != nil {
		log.Println(err)
		return false
	}
	if !strings.Contains(auth.Target, ":") {
		auth.Target += ":21"
	}
	var c *ftp.ServerConn
	// c, ok := connections[auth.Target]
	// if !ok || used > 10 {
	for i := 0; i < 8; i++ {

		c, err = ftp.Dial(auth.Target, ftp.DialWithTimeout(time.Duration(DEFAULT_TIMEOUT)*time.Second))
		if err != nil {
			if err.Error() == "421 50 users (the maximum) are already logged in, sorry" {
				time.Sleep(5 * time.Second)
			} else {

				// log.Println(err)
			}

		} else {
			defer c.Quit()
			break

		}

	}
	if err != nil {
		if err.Error() == "421 50 users (the maximum) are already logged in, sorry" {
			NeedRetry <- string(ftpb)
		}
		return false
	}

	// lock.Lock()
	// connections[auth.Target] = c
	// used = 1
	// lock.Unlock()

	// }

	err = c.Login(auth.User, auth.Pwd)
	used++
	if err != nil {

		// log.Println(err)
		return false
	}
	return true
}
